import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout'
import Article from '../views/Article'
import Collect from '../views/Collect'
import Like from '../views/Like'
import User from '../views/User'
import ArticleDetail from '../views/ArticleDetail'
import Login from '../views/Login'
import Register from '../views/Register'
import { getToken } from '@/api/storage'
import { Toast } from 'vant'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: 'article', component: Article },
        { path: 'collect', component: Collect },
        { path: 'like', component: Like },
        { path: 'user', component: User }
      ]
    },
    { path: '/detail/:id', component: ArticleDetail },
    { path: '/login', component: Login },
    { path: '/register', component: Register }
    // { name: 'collect', path: '/collect/:words?', component: Collect },

  ]
})

// 全局前置守卫：
// 1. 所有的路由一旦被匹配到，在真正渲染解析之前，都会先经过全局前置守卫
// 2. 只有全局前置守卫放行，才能看到真正的页面
// 任何路由，被解析访问前，都会先执行这个回调
// 1. from 你从哪里来， 从哪来的路由信息对象
// 2. to 你往哪里去， 到哪去的路由信息对象
// 3. next() 是否放行，如果next()调用，就是放行 => 放你去想去的页面
const whiteList = ['/login', '/register']
router.beforeEach((to, form, next) => {
  if (getToken() || whiteList.includes(to.path)) {
    next()
  } else {
    Toast.fail('gun')
    next('/login')
  }
})

export default router
